<template>
  <div class="medication-records">
    <el-card class="medication-card">
      <template #header>
        <div class="card-header">
          <h2>用药记录</h2>
          <div class="header-actions">
            <el-button type="primary" size="small" @click="showAddMedicationDialog = true">添加记录</el-button>
            
          </div>
        </div>
      </template>
      <div class="medication-content">
        <div class="filters-section">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索药品名称..."
                clearable
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </el-col>
            <el-col :span="6">
              <el-select v-model="statusFilter" placeholder="用药状态" clearable>
                <el-option label="正在服用" value="正在服用" />
                <el-option label="已完成" value="已完成" />
                <el-option label="已暂停" value="已暂停" />
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 100%"
              />
            </el-col>
            <el-col :span="4">
              <el-button type="primary" @click="applyFilters">筛选</el-button>
              <el-button type="primary" @click="resetFilters">重置</el-button>
            </el-col>
          </el-row>
        </div>
        
        <div class="table-section">
          <el-table 
            :data="medicationRecords" 
            style="width: 100%"
            :header-cell-style="{ background: '#fafafa', color: '#333', fontWeight: '600' }"
            stripe
            v-loading="loading"
          >
            <el-table-column prop="date" label="日期" width="120" sortable>
              <template #default="{ row }">
                <span class="date-text">{{ formatDate(row.date) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="medicationName" label="药品名称" width="180">
              <template #default="{ row }">
                <div class="medication-info">
                  <span class="medication-name">{{ row.medicationName }}</span>
                  <el-tag 
                    :type="getStatusType(row.status)" 
                    size="small"
                    class="status-tag"
                  >
                    {{ getStatusText(row.status) }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="dosage" label="剂量" width="120">
              <template #default="{ row }">
                <span class="dosage-text">{{ row.dosage }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="frequency" label="频次" width="120">
              <template #default="{ row }">
                <span class="frequency-text">{{ row.frequency }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="duration" label="疗程" width="120">
              <template #default="{ row }">
                <span class="duration-text">{{ row.duration }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="doctor" label="开药医生" width="120">
              <template #default="{ row }">
                <span class="doctor-text">{{ row.doctor || '暂无' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120">
              <template #default="{ row }">
                <span class="status-text">{{ row.status }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="notes" label="备注" show-overflow-tooltip>
              <template #default="{ row }">
                <span class="notes-text">{{ row.notes || '无' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="editRecord(row)">编辑</el-button>
                <el-button type="danger" size="small" @click="deleteMedication(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="pagination-wrapper">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="totalRecords"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
      <!-- 用药记录对话框 -->
    <el-dialog v-model="showAddMedicationDialog" title="添加用药记录" width="500px">
      <el-form ref="medicationFormRef" :model="medicationForm" :rules="addMedicationRules" label-width="100px">
        <el-form-item label="日期" prop="date">
          <el-date-picker
            v-model="medicationForm.date"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="药品名称" prop="medicationName">
          <el-input v-model="medicationForm.medicationName" placeholder="请输入药品名称" />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="剂量" prop="dosage">
              <el-input v-model="medicationForm.dosage" placeholder="如：1片" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="频次" prop="frequency">
              <el-input v-model="medicationForm.frequency" placeholder="如：每日3次" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="疗程" prop="duration">
          <el-input v-model="medicationForm.duration" placeholder="如：7天" />
        </el-form-item>

        <el-form-item label="开药医生" prop="doctor">
          <el-input v-model="medicationForm.doctor" placeholder="如：张三" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="medicationForm.status" placeholder="请选择状态">
            <el-option label="正在服用" value="正在服用" />
            <el-option label="已完成" value="已完成" />
            <el-option label="已暂停" value="已暂停" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="备注" prop="notes">
          <el-input
            v-model="medicationForm.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showMedicationDialog = false">取消</el-button>
        <el-button type="primary" @click="saveMedicationRecord">保存</el-button>
      </template>
    </el-dialog>
      <!-- 添加用药记录对话框 -->
    <el-dialog v-model="showMedicationDialog" title="更改用药记录" width="500px">
      <el-form ref="medicationFormRef" :model="medicationForm" :rules="medicationRules" label-width="100px">
        <el-form-item label="日期" prop="date">
          <el-date-picker
            v-model="medicationForm.date"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="药品名称" prop="medicationName">
          <el-input v-model="medicationForm.medicationName" placeholder="请输入药品名称" />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="剂量" prop="dosage">
              <el-input v-model="medicationForm.dosage" placeholder="如：1片" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="频次" prop="frequency">
              <el-input v-model="medicationForm.frequency" placeholder="如：每日3次" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="疗程" prop="duration">
          <el-input v-model="medicationForm.duration" placeholder="如：7天" />
        </el-form-item>

        <el-form-item label="状态" prop="status"> 
          <el-select v-model="medicationForm.status" placeholder="请选择">
            <el-option label="正在服用" value="正在服用"></el-option>
            <el-option label="已完成" value="已完成"></el-option>
            <el-option label="已暂停" value="已暂停"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="备注" prop="notes">
          <el-input
            v-model="medicationForm.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showMedicationDialog = false">取消</el-button>
        <el-button type="primary" @click="setMedicationRecord">保存</el-button>
      </template>
    </el-dialog>
      
      <div v-if="!medicationRecords.length" class="no-data-container">
        <el-empty description="暂无用药记录" :image-size="200">
          <el-button type="primary">添加第一条记录</el-button>
        </el-empty>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive } from 'vue'
import { useUserStore } from '@/stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getALLMedicationDataById } from '@/api/medicationinfo/medicationinfo'
import { type MedicationRecord } from '@/stores/elderly'
import { useRoute } from 'vue-router'
import {setMedicationData,addMedicationData,deleteMedicationData,medicationDataFilter} from '@/api/medicationinfo/medicationinfo'

const userStore = useUserStore()
const elderlyId = ref(localStorage.getItem('elderlyId') || '')
const route = useRoute()
const searchKeyword = ref('')
const statusFilter = ref('')
const dateRange = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const medicationFormRef = ref()
const showMedicationDialog = ref(false)
const showAddMedicationDialog = ref(false)
const medicationForm = reactive({
  id: '',
  elderlyId: '',
  date: '',
  medicationName: '',
  dosage: '',
  frequency: '',
  duration: '',
  doctor: '',
  status: '',
  notes: ''
})

function formatDateForBackend(date: Date | string | null): string | undefined {
  if (!date) return undefined
  return new Date(date).toISOString() // 输出 ISO 格式："2025-07-16T00:00:00Z"
}

function mapStatusToBackend(status: string): string | undefined {
  const statusMap: Record<string, string> = {
    '正在服用': '正在服用',
    '已完成': '已完成',
    '已暂停': '已暂停'
  }
  return statusMap[status] || status
}

const filterMedicationForm = reactive({
  datestart: '',
  dateend: '',
  status: '',
  elderlyId: '',
  medicationName: ''
})


const medicationRules = {
  date: [{ required: false, message: '请选择日期', trigger: 'change' }],
  medicationName: [{ required: false, message: '请输入药品名称', trigger: 'blur' }],
  dosage: [{ required: false, message: '请输入剂量', trigger: 'blur' }],
  frequency: [{ required: false, message: '请输入频次', trigger: 'blur' }],
  duration: [{ required: false, message: '请输入疗程', trigger: 'blur' }],
  notes: [{ required: false, message: '请输入备注', trigger: 'blur' }]
}
const addMedicationRules = {
  date: [{ required: true, message: '请选择日期', trigger: 'change' }],
  medicationName: [{ required: true, message: '请输入药品名称', trigger: 'blur' }],
  dosage: [{ required: true, message: '请输入剂量', trigger: 'blur' }],
  frequency: [{ required: true, message: '请输入频次', trigger: 'blur' }],
  duration: [{ required: true, message: '请输入疗程', trigger: 'blur' }],
  doctor: [{ required: true, message: '请输入医生名称', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  notes: [{ required: true, message: '请输入备注', trigger: 'blur' }]
}
//重置页面记录表单
const resetFilters = async () => {
  searchKeyword.value = ''
  statusFilter.value = ''
  dateRange.value = [],[]
  await getMedicationRecords()
}
// 添加用药记录
const saveMedicationRecord = async () => {
  if (!medicationFormRef.value) return
  
  try {
    await medicationFormRef.value.validate()
    
    const record = {
      ...medicationForm,
      elderlyId: elderlyId.value,
      date: new Date(medicationForm.date).toISOString()
    }

    const response = await addMedicationData(record)
     if (response.code !== 200) {
      ElMessage.error(response.message || '用药记录添加失败')
      return
    }
    
    ElMessage.success('用药记录添加成功')
    showAddMedicationDialog.value = false
    getMedicationRecords()
  } catch (error) {
    console.error('保存失败:', error)
  }
}

//删除用药记录
const deleteMedication = async (record: MedicationRecord) => {
  try {
    await ElMessageBox.confirm('确定要删除这条用药记录吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 这里应该调用API删除记录
    await deleteMedicationData(record.id);
    ElMessage.success('删除成功')
    getMedicationRecords()
  } catch {
    // 用户取消
  }
}
//编辑用药记录
const setMedicationRecord = async () => {
  if (!medicationFormRef.value) return

  try {
    await medicationFormRef.value.validate()

    // 验证日期是否有效
    let dateValue = null
    if (medicationForm.date) {
      const dateObj = new Date(medicationForm.date)
      if (dateObj.toString() !== 'Invalid Date' && !isNaN(dateObj.getTime())) {
        dateValue = dateObj.toISOString()
      } else {
        console.error('日期无效:', medicationForm.date)
        ElMessage.error('请选择有效的日期')
        return
      }
    }
    
    const record = {
      ...medicationForm,
      id: medicationForm.id,
      elderlyId: elderlyId.value,
      date: dateValue
    }

    console.log('提交数据:', record)
    const response = await setMedicationData(medicationForm.id, record)
    
    ElMessage.success('用药记录更改成功')
    showMedicationDialog.value = false
    
    // 可选：刷新记录列表
    getMedicationRecords()
    
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存用药记录失败，请重试')
  }
 
}

const medicationRecords = ref<MedicationRecord[]>([])
const totalRecords = ref(0)
// 获取用药记录
const getMedicationRecords = async () => {
  if (!elderlyId.value) return
  loading.value = true
  const res = await getALLMedicationDataById(elderlyId.value)
  medicationRecords.value = res.data
  totalRecords.value = res.data.length
  loading.value = false
}

const formatDate = (date: string) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    active: 'success',
    completed: 'info',
    paused: 'warning'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {

    active: '正在服用',
    completed: '已完成',
    paused: '已暂停'
  }
  return statusMap[status] || '未知'
}
//筛选用药记录
const applyFilters = async () => {
  currentPage.value = 1
  const dateValues = dateRange.value ? dateRange.value : ['', '']
  // 这里可以添加筛选逻辑
    const record = {
    medicationName: searchKeyword.value.trim(),
    dateStart: formatDateForBackend(dateValues[0]||''), // 转换为 ISO 格式
    dateEnd: formatDateForBackend(dateValues[1]||''),
    status: mapStatusToBackend(statusFilter.value),
    elderlyId: elderlyId.value
  }
    

  console.log(record)

  loading.value = true
  try { 
    const response = await medicationDataFilter(record)
    medicationRecords.value = response.data
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('无搜索数据，请输入数据或重置')
  }
  finally {
    loading.value = false
  }

}



const editRecord = (row: any) => {
  console.log('编辑记录:', row)
  Object.assign(medicationForm, row) // 将 row 数据复制到 medicationForm
  showMedicationDialog.value = true
}

const toggleStatus = (row: any) => {
  console.log('切换状态:', row)
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
}

onMounted(async () => {
  // 初始化数据
  await getMedicationRecords()
  console.log('elderlyId:', elderlyId.value)
})
</script>

<style scoped>
.medication-records {
  height: 130%;
  width: 100%;
}

.medication-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.medication-card :deep(.el-card__body) {
  flex: 1;
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.medication-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.filters-section {
  padding: 24px;
  background: #fafafa;
  border-bottom: 1px solid #e6e6e6;
}

.table-section {
  flex: 1;
  padding: 24px;
  display: flex;
  flex-direction: column;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.medication-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.medication-name {
  font-weight: 500;
  color: #333;
}

.status-tag {
  font-size: 12px;
}

.date-text {
  color: #666;
  font-size: 14px;
}

.dosage-text {
  font-weight: 500;
  color: #409eff;
}

.frequency-text {
  color: #67c23a;
}

.duration-text {
  color: #e6a23c;
}

.doctor-text {
  color: #909399;
}

.notes-text {
  color: #666;
  font-style: italic;
}

.warning-text {
  color: #e6a23c;
}

.no-data-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 40px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .filters-section {
    padding: 20px;
  }
  
  .table-section {
    padding: 20px;
  }
}

@media (max-width: 768px) {
  .filters-section {
    padding: 16px;
  }
  
  .table-section {
    padding: 16px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .filters-section .el-row {
    margin: 0;
  }
  
  .filters-section .el-col {
    margin-bottom: 12px;
  }
}
</style> 